#include <iostream>
using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution
{
public:
    bool isPalindrome(ListNode *head)
    {
        if(head == nullptr){
            return true;
        }

        // 使用快慢指针找到前半部分链表的结束位置
        ListNode *firstHalfListEnd = findSecondHalf(head);
        // 翻转后半部分链表
        ListNode* secondHalfListList = reverseLinkedList(firstHalfListEnd->next);
        // 判断是否是回文
        ListNode *p1 = head;
        ListNode *p2 = secondHalfListList;
        bool result = true;
        while(result && p2 != nullptr){
            if(p1->val != p2->val){
                result = false;
            }
            p1 = p1->next;
            p2 = p2->next;
        }
        // 还原链表
        firstHalfListEnd->next = reverseLinkedList(secondHalfListList);
        return result;
    }

    ListNode* findSecondHalf(ListNode* head){
        ListNode *fast = head;
        ListNode *slow = head;
        while(fast->next != nullptr && fast->next->next != nullptr){
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }

    ListNode* reverseLinkedList(ListNode* head){
        ListNode *pre = nullptr;
        ListNode *cur = head;
        while(cur != nullptr){
            ListNode *temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};